package com.slashvision.im.chat

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.MediaController
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.slashvision.im.SLog
import com.slashvision.im.databinding.FragmentVideoPreviewBinding
import com.slashvision.im.tool.dutil.DUtil
import com.slashvision.im.tool.dutil.callback.DownloadCallback
import com.slashvision.im.tool.dutil.data.Consts
import com.slashvision.im.tool.dutil.download.DownloadManger
import java.io.File



/**
 * author : lizhenxin
 *  date  : 2021/10/15
 *  desc  :
 */
/**
 * @desc:
 * @author: LiZhenxin
 * @create:
 * update
 **/
const val KEY_URL = "_KEY_URL_"

class VideoPreviewFragment : Fragment() {

    companion object {
        fun newInstance(bundle: Bundle): VideoPreviewFragment {
            return VideoPreviewFragment().apply {
                bd = bundle
            }
        }
    }

    private var bd: Bundle? = null


    private lateinit var url: String
    private lateinit var oPath:String
    private lateinit var path: String
    private lateinit var name:String
    
    private lateinit var player: ExoPlayer

    private lateinit var binding: FragmentVideoPreviewBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentVideoPreviewBinding.inflate(inflater, container, false)
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.back.setOnClickListener {
            findNavController().navigateUp()
        }

        url = bd?.getString(KEY_URL, "")?:""
        oPath = bd?.getString(KEY_PATH, "")?:""
        path = oPath.substring(0, oPath.lastIndexOf("/"))
        name = oPath.substring(oPath.lastIndexOf("/") + 1, oPath.length)

        // /data/user/0/com.slashvision.im/cache/video/20211020143014.mp4
        SLog.d(TAG_IM, "视频url：${url},  path: ${path}, name: ${name}")


        if (isVideoExit()) {
            playVideo()
        } else {
            downloadVideo()
        }

        /*File(path).takeIf { it.exists() }?.delete()
        downloadVideo(url, path)*/
    }


    private fun isVideoExit() = File("${path}/${name}").exists()

    private fun downloadVideo() {
        DUtil.init(requireContext()).url(url).path(path).name(name).build().start(object : DownloadCallback {
            override fun onStart(currentSize: Long, totalSize: Long, progress: Float) {
                binding.progress.visibility = View.VISIBLE
            }

            override fun onProgress(currentSize: Long, totalSize: Long, progress: Float) {
                binding.progress.text = "下载中：${progress} %"
            }

            override fun onPause() {
            }

            override fun onCancel() {
            }

            override fun onFinish(file: File?) {
                binding.progress.visibility = View.GONE
                playVideo()
            }

            override fun onWait() {
            }

            override fun onError(error: String?) {
            }

        })
    }

    /*
    * path: /data/user/0/com.slashvision.im/cache/video/20211020160607.mp4
    * uri:  /data/user/0/com.slashvision.im/cache/video/20211020160607.mp4
    *
    * path: /data/user/0/com.slashvision.im/cache/video/20211020160627.mp4
    * uri:  /data/user/0/com.slashvision.im/cache/video/20211020160627.mp4
    * */
    private fun playVideo() {
        /*val uri = Uri.parse("${oPath}")
        SLog.d(TAG_IM, "视频路径： path: ${oPath}\n uri:${uri}")
        val ms = buildMediaSource(uri)
        player = SimpleExoPlayer.Builder(requireContext()).build().apply {
            playWhenReady = true
            prepare(ms, true, false)
        }
        binding.previewVideo.player = player*/
        SLog.d(TAG_IM, "视频路径： path: -${oPath}-\n")
        val mc = MediaController(requireContext())
        binding.previewVideo.apply {
            setVideoPath(oPath)
            setMediaController(mc)
            setOnPreparedListener {
                it.isLooping = true
            }
            setOnInfoListener { mp, what, extra ->
                SLog.d(TAG_IM, "info:  ${what}: ${extra}")
                true
            }
            start()
            requestFocus()
        }
    }

    private fun buildMediaSource(uri: Uri): MediaSource {
        val dataSourceFactory =
            DefaultDataSourceFactory(requireContext(), "com.slashvision.im")
        return ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
    }


    override fun onStop() {
        super.onStop()
        if (::player.isInitialized) {
            player.release()
        }
        if (::url.isInitialized) {
            DownloadManger.getInstance(requireContext()).getCurrentData(url)?.let {
                val status = it.status
                if (status != Consts.CANCEL && status != Consts.FINISH && status != Consts.DESTROY) {
                    DownloadManger.getInstance(requireContext()).cancel(url)
                }
            }
        }
    }
}